//
//  EmojiArtDocument.swift
//  EmojiArtDocument
//
//  Created by durban.zhang on 2020/10/30.
//

import Foundation
import SwiftUI

class EmojiArtDocument: ObservableObject {
    static let palatte: String = "😄🚄🎈🌞🌛"
    
    @Published private var emojiArt: EmojiArt = EmojiArt()
    
    @Published private(set) var backgroundImage: UIImage?
    
    var emojis: [EmojiArt.Emoji]{ emojiArt.emojis }
//    private let backgroundImage: URL?
    
    func addEmoji(text: String, at location: CGPoint, size: CGFloat) {
        emojiArt.addEmoji(text, x: Int(location.x), y: Int(location.y), size: Int(size))
    }
    
    func moveEmoji(_ emoji: EmojiArt.Emoji, by offset: CGSize) {
        if let index = emojiArt.emojis.firstIndex(matching: emoji) {
            emojiArt.emojis[index].x += Int(offset.width)
            emojiArt.emojis[index].y += Int(offset.height)
        }
    }
    
    func scaleEmoji(_ emoji: EmojiArt.Emoji, by scale: CGFloat) {
        if let index = emojiArt.emojis.firstIndex(matching: emoji) {
            emojiArt.emojis[index].size = Int((scale * CGFloat(emojiArt.emojis[index].size)).rounded(.toNearestOrEven))
        }
    }
    
    func setBackgroundUrl(_ url: URL?) {
        emojiArt.backgroundUrl = url?.imageURL
        fetchBackgroundImage()
    }
    
    private func fetchBackgroundImage() {
        backgroundImage = nil
        
        if let url = self.emojiArt.backgroundUrl {
            DispatchQueue.global(qos: .userInitiated).async {
                if let imageData = try? Data(contentsOf: url) {
                    DispatchQueue.main.async {
                        self.backgroundImage = UIImage(data: imageData)
                    }
                }
            }
        }
    }
}

extension EmojiArt.Emoji {
    var fontSize: CGFloat {CGFloat(self.size) }
    var location: CGPoint { CGPoint(x: CGFloat(x), y: CGFloat(y)) }
}
